
const http = require('http');
const fs = require('fs');
const path = require('path');
const cmder = require('child_process');

const cssFile = path.resolve(__dirname, '../public/iconfont.css');
const jsonFile = path.resolve(__dirname, '../src/components/myIcon.json');

let args = process.argv.splice(2);

function err() {
  console.log('please set the css url');
  console.log('you can use -g \n\t to set the url');
}



if (args.length === 0){
  err();
  return;
}
const cmd = args[0];
const param = args[1];
console.log(cmd,param);
let url = null;
if (cmd === 'g'&&param){
  url = param;
  if (!url.match('http')){
    url='http://'+param;
  }
}

if (!url){
  err();
  return;
}

http.get(url, function(req, res) {
    var html = '';
    req.on('data', function(data) {
        html += data;
    });
    req.on('end', function() {
        // console.info(html);
        generateCss(html);
        generateJson(html);
    });
});


function generateCss(html) {
  fs.writeFile(cssFile,html,(error)=>{
    if(error){
      throw new Error(error);
    }else {
      console.log('generate '+cssFile+' success!!');
    }
  });
}

function generateJson(html) {
  var origin =  html.match(/.icon-.*?}/g);
  var datas = '[\n\t';
  origin.map((item,index)=>{

    var d = item.split(':');
    console.log(d);
    datas+="\t\""+`${d[0].replace('.','')}`+"\""+(index===origin.length-1?'\n':',\n');
  });
  datas+=']';
  fs.writeFile(jsonFile,datas,(error)=>{
    if(error){
      throw new Error(error);
    }else {
      console.log('generate '+jsonFile+' success!!');
    }
  });
}
